//
//  PayTypeViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "PayTypeViewController.h"
#import "Order.h"
#import "OrderProductPay.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DataSigner.h"
#import "payRequsestHandler.h"
@interface PayTypeViewController ()
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIButton *payButton;
@property (weak, nonatomic) IBOutlet UILabel *leftMoney;
@property(nonatomic,assign)NSInteger selectedIndex;
@property (weak, nonatomic) IBOutlet UIView *maskView;
@end

@implementation PayTypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedIndex = 90;
    // Do any additional setup after loading the view.
    //保存订单id
    if (self.payId) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setObject:self.payId forKey:@"orderId"];
        [Common setMutableData:data];
    }
    [self initViewlayout];
    [self getAccountLeftMoney];
}


- (void)initViewlayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    _scroView.contentSize = flexibleSize(CGSizeMake(320, 505), NO);
    _payButton.layer.masksToBounds = YES;
    _payButton.layer.cornerRadius = 21*VerticalRatio();
    
    if ([_payTypes isEqualToString:@"2"]) {
        _maskView.hidden= NO;
        _payButton.frame = flexibleFrame(CGRectMake(13, 155, 294, 42), NO);
    }
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark === 查询账户余额
- (void)getAccountLeftMoney{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMemberMuseEpurseInfoById withHttpType:@"POST" withTag:HK_HK_queryMemberMuseEpurseInfoById];
}


#pragma mark == 选择支付方式
- (IBAction)chosePayType:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.tag == _selectedIndex) {
        return;
    }
    UIButton * button = [self.view viewWithTag:_selectedIndex];
    button.selected = NO;
    _selectedIndex = sender.tag;
}

#pragma mark == 确认支付
- (IBAction)surePay:(id)sender {
    //支付宝配置信息
    [self getPaymentDetailInfo];
}
#pragma   mark  请求支付配置信息 ======================================
- (void)getPaymentDetailInfo{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
        if (_selectedIndex == 100) {
        //支付宝
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:HK_getAlipayInfo withHttpType:@"POST" withTag:HK_HK_HK_getAlipayInfo];
        }else if (_selectedIndex == 101) {
            //微信支付
            NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
            [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
            [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
            [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
            self.shareApi.delegate=self;
            [self.shareApi  requestOperationWithDic:dic withPath:HK_getWxpayInfo withHttpType:@"POST" withTag:HK_HK_getWxpayInfo];
        }else if (_selectedIndex == 102){//余额支付
            NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
            [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
            [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
            [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
            [dic setObject:_payId forKey:@"orderNo"];
            self.shareApi.delegate=self;
            [self.shareApi  requestOperationWithDic:dic withPath:HK_payByMemberEpurse withHttpType:@"POST" withTag:HK_HK_payByMemberEpurse];
        
        }

    
}
#pragma   mark  跳转支付宝支付======================================
- (void)userAlibabaPaymentClick:(NSDictionary *)payDta{
    //实例并初始化订单信息
    OrderProductPay *product = [[OrderProductPay alloc] init];
    product.subject = self.payOrderName;
    product.body = self.payOrderName;
    product.price = [self.payOrderPrice floatValue];
    
    NSString *partner = [payDta objectForKey:@"payPartner"];
    NSString *seller = [payDta objectForKey:@"paySellAccount"];
    NSString *privateKey = [payDta objectForKey:@"payPrivate"];
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _payId; //订单ID（由商家自行制定）
    order.productName = product.subject; //商品标题
    order.productDescription = product.body; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
    order.notifyURL =  [payDta objectForKey:@"AlipayNotifyUrl"]; //回调URL
    //    order.notifyURL = @"http://www.baidu.com";
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"Housekeeping";
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                //传递支付成功信息
                //支付成功
                [self paymentWenxinAndZhifubaoSuccess:@"1"];

            }
        }];
        
    }
}

#pragma   mark  跳转微信支付====
- (void)sendPay_demo:(NSDictionary *)payDta
{
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [[payRequsestHandler alloc] init];
    //初始化支付签名对象
    //    [req init:APP_ID mch_id:MCH_ID];
    [req init:[payDta objectForKey:@"optyAppId"] mch_id:[payDta objectForKey:@"wxmchid"]];
    //设置密钥
    [req setKey:[payDta objectForKey:@"optyAppKey"]];
    
    //}}}
    //组装支付参数数据
    NSMutableDictionary *payData = [NSMutableDictionary dictionary];
    [payData setObject:[payDta objectForKey:@"optyAppId"] forKey:@"wxappid"];
    [payData setObject:[payDta objectForKey:@"optyMchId"] forKey:@"wxmchid"];
    [payData setObject:[payDta objectForKey:@"optyAppKey"] forKey:@"wxkey"];
    [payData setObject:[payDta objectForKey:@"optyNotifyUrl"] forKey:@"WXNotifyUrl"];
    [payData setObject:self.payOrderName forKey:@"orderName"];
    [payData setObject:_payId forKey:@"ordernumber"];
    [payData setObject:self.payOrderName forKey:@"orderContent"];
    [payData setObject:self.payOrderPrice forKey:@"orderPrice"];
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo:payData];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [self alert:@"提示信息" msg:debug];
        
        //        NSLog(@"%@\n\n",debug);
    }else{
        //        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
        
    }
}

//微信支付成功回调
-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                //                strMsg = @"支付结果：成功！";
                //                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                //传递支付成功信息
                
              
            //支付成功
            [self paymentWenxinAndZhifubaoSuccess:@"1"];
                
                
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！"];
                //                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                break;
        }
    }
}



//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
    
}

//第三方支付成功调支付接口
- (void)paymentWenxinAndZhifubaoSuccess:(NSString *)payType{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    [dic setObject:locationString forKey:@"payTime"];
    [dic setObject:payType forKey:@"payment"];
    
    [dic setObject:@"" forKey:@"tradeNo"];
    NSMutableDictionary *data = [Common getMutableData];
    [dic setObject:[data objectForKey:@"orderId"] forKey:@"outTradeNo"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    if (!self.shareApi) {
        self.shareApi=[LQRequestApi sharedInstance];
    }
    self.shareApi.delegate=self;
   [self.shareApi  requestOperationWithDic:dic withPath:HK_payOrder withHttpType:@"POST" withTag:HK_HK_payOrder];
    
}


#pragma   mark  ======================================
#pragma   mark GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    self.view.userInteractionEnabled = YES;
    
    if (tag == HK_HK_HK_getAlipayInfo){
        //支付宝配置信息
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableDictionary *data = [NSMutableDictionary dictionary];
                [data setObject:database[@"result"][@"optyMchId"] forKey:@"payPartner"];
                [data setObject:database[@"result"][@"optyAppId"] forKey:@"paySellAccount"];
                [data setObject:database[@"result"][@"optyPrivateKey"] forKey:@"payPrivate"];
                [data setObject:database[@"result"][@"optyNotifyUrl"] forKey:@"AlipayNotifyUrl"];
                //支付宝
                [self userAlibabaPaymentClick:data];
            });
            
        }
    }else if (tag == HK_HK_getWxpayInfo){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableDictionary *data = database[@"result"];
                //微信
                [self sendPay_demo:data];
            });
            
        }
    } else if (tag == HK_HK_payOrder){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
            
        }else{
           
            [[Common getNavigation]popViewControllerWithCompletion:^{
                 [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"hadPay" object:@"1"];
            }];
           
            
        }
    }else if (tag == HK_HK_queryMemberMuseEpurseInfoById){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _leftMoney.text = [NSString stringWithFormat:@"可以余额：￥%.2f",[database[@"result"][@"museEpurse"]floatValue]];
        }
    }else if (tag ==HK_HK_payByMemberEpurse  ){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
           
            [[Common getNavigation]popViewControllerWithCompletion:^{
               [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"hadPay" object:@"1"];
            }];
            
        }
    
    
    }

}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    self.view.userInteractionEnabled = YES;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
